/*
 * @Author: wangjh wangjiahui0710@163.com
 * @Date: 2024-05-20 16:40:44
 * @LastEditors: wangjh wangjiahui0710@163.com
 * @LastEditTime: 2024-05-29 09:51:02
 * @FilePath: \hn-fire-product-mobile\src\utils\request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { showToast } from '@nutui/nutui';
import type { AxiosRequestConfig } from 'axios';
import axios from 'axios';

function createInstance(config: AxiosRequestConfig = {}) {
  const instance = axios.create({
    timeout: 50000,
    headers: {
      'Content-Type': 'application/json',
    },
    maxRedirects: 0,
    ...config,
  });
  instance.interceptors.request.use((config) => {
    return config;
  });
  instance.interceptors.response.use(
    (response) => {
      // const mainStore = useMainStore();

      const code = +response.data?.code;
      if (code) {
        if ([4001, 4002, 4003, 4004, 4005].includes(code)) {
          // mainStore.logout();
          // const userStore = useUserStore();
          // userStore.cleanLogin();
        }

        if (code >= 400 && response.data.message !== '用户已离线') {
          console.error(response);
          const message = response?.data?.message || '请求异常';
          showToast.text(message);
          return Promise.reject(response);
        }
      }
      return response;
    },
    (error = {}) => {
      const message = error.response?.data?.message || '请求异常';
      showToast.text(message);
      return Promise.reject(error);
    },
  );
  return instance;
}

const instance = createInstance();

export async function fireRequest<T>(params: AxiosRequestConfig<T>) {
  const res = await instance.request({
    baseURL: import.meta.env.VITE_SERVER_URL,
    ...params,
  });
  return res.data;
}
